package com.chinacoal.microservice.impl.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.chinacoal.microservice.api.OrgOpenClient;
import com.chinacoal.microservice.api.SysCenterApi;
import com.chinacoal.microservice.api.model.QueryUtaskParam;
import com.chinacoal.microservice.api.model.UtaskCompleteTaskParam;
import com.chinacoal.microservice.api.model.entity.UtaskInfoEntity;
import com.chinacoal.microservice.api.model.resource.UnionTaskVar;
import com.chinacoal.microservice.exception.MessageException;
import com.chinacoal.microservice.impl.mapper.UtaskInfoMapper;
import com.chinacoal.microservice.impl.service.UtaskInfoService;
import com.chinacoal.microservice.impl.util.UtaskCommonFun;
import com.chinacoal.microservice.model.organization.vo.EmployeeVO;
import com.chinacoal.microservice.model.syscenter.SysUserMap;
import com.chinacoal.microservice.util.PrimaryKey;
import com.chinacoal.microservice.util.result.CodeMsg;
import com.chinacoal.microservice.util.result.Result;

@Service
public class UtaskInfoServiceImpl extends ServiceImpl<UtaskInfoMapper, UtaskInfoEntity> implements UtaskInfoService {

    @Resource
    private UtaskInfoMapper utaskInfoMapper;
    @Resource
    private SysCenterApi  sysCenterApi;
    @Resource
    private OrgOpenClient orgOpenClient;

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public Result<Object> addTask(UtaskInfoEntity utaskInfoEntity) throws Exception {
		
		// 转换用户
		String sysTaskId = utaskInfoEntity.getSysTaskId();
		String sysCode = utaskInfoEntity.getSysCode();
		String sendUserId = utaskInfoEntity.getSendUserId();
		String sendUserName = utaskInfoEntity.getSendUserName();
		String handleUserId = utaskInfoEntity.getHandleUserId();
		String handleUserName = utaskInfoEntity.getHandleUserName();
		String isInternal = utaskInfoEntity.getIsInternal();
		Integer createdBy = null; 
		
		// 上一环节审批人名称
		if("Y".equals(isInternal)) {
			
		}else if(StringUtils.isNotEmpty(sendUserId)){
			Result<SysUserMap> sendUserResult = sysCenterApi.getUserMap(sysCode, "default", sendUserId);
			if(sendUserResult.getCode() == 10000 && sendUserResult.getData() != null) {
				sendUserName = sendUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				sendUserName = sendUserId;
			}
		}
		
		// 当前审批人名称
		if("Y".equals(isInternal)) {
			/*
			 * Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null,
			 * handleUserId); if(empResult.getCode() == 10000 && empResult.getData() != null
			 * && empResult.getData().getUser() != null) { EmployeeVO employeeVO =
			 * empResult.getData(); sendUserName = employeeVO.getUser().getName(); createdBy
			 * = employeeVO.getUser().getUserAccountId(); }else { sendUserName = sendUserId;
			 * }
			 */
			createdBy = Integer.valueOf(handleUserId);
		}else {
			Result<SysUserMap> handleUserResult = sysCenterApi.getUserMap(sysCode, "default", handleUserId);
			if(handleUserResult.getCode() == 10000 && handleUserResult.getData() != null) {
				handleUserName = handleUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				handleUserName = handleUserId;
			}
			createdBy = handleUserResult.getData().getUserId();
		}
		
		// 校验
		QueryUtaskParam param = new QueryUtaskParam();
		param.setSysTaskId(sysTaskId);
		param.setUserCode(handleUserId);
		Integer count = utaskInfoMapper.getTaskInfoListNum(param);
		if(count != null && count > 0) {
			return Result.error(CodeMsg.ERROR_UTASK_REPEAT_ADD.fillArgs("待办已存在，请勿重复新增"));
		}
		
		// 新增待办
		utaskInfoEntity.setTaskId(PrimaryKey.newKey());
		utaskInfoEntity.setSendUserId(sendUserId);
		utaskInfoEntity.setSendUserName(sendUserName);
		utaskInfoEntity.setHandleUserId(handleUserId);
		utaskInfoEntity.setHandleUserName(handleUserName);
		utaskInfoEntity.setCreatedBy(createdBy);
		utaskInfoEntity.setCreationDate(new Date());
		utaskInfoEntity.setCreatedByName(handleUserName);
		utaskInfoMapper.insert(utaskInfoEntity);
		
		return Result.success("新增待办成功");
	}

	@Override
	public Map<String, List<UtaskInfoEntity>> battchTaskAdd(List<UtaskInfoEntity> taskInfoList) throws Exception {
		
		Map<String, List<UtaskInfoEntity>> resultMap = new HashMap<String, List<UtaskInfoEntity>>();
		List<UtaskInfoEntity> successList = new ArrayList<UtaskInfoEntity>();
		List<UtaskInfoEntity> errorList = new ArrayList<UtaskInfoEntity>();
		
		for (UtaskInfoEntity utaskInfoEntity : taskInfoList) {
			try {
				Result<Object> insertTaskInfoResult = addTask(utaskInfoEntity);
				if(insertTaskInfoResult.getCode() == 10000 || insertTaskInfoResult.getCode() == 70000) {
					successList.add(utaskInfoEntity);
				}else {
					errorList.add(utaskInfoEntity);
				}
			} catch (Exception e) {
				errorList.add(utaskInfoEntity);
			}
		}
		
		resultMap.put("success", successList);
		resultMap.put("error", errorList);
		
		return resultMap;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void updateTask(UtaskInfoEntity utaskInfoEntity) throws Exception {
		
		// 转换用户
		String sysTaskId = utaskInfoEntity.getSysTaskId();
		String sysCode = utaskInfoEntity.getSysCode();
		String sendUserId = utaskInfoEntity.getSendUserId();
		String sendUserName = utaskInfoEntity.getSendUserName();
		String handleUserId = utaskInfoEntity.getHandleUserId();
		String handleUserName = utaskInfoEntity.getHandleUserName();
		String isInternal = utaskInfoEntity.getIsInternal();
		Integer createdBy = null; 
		
		// 上一环节审批人名称
		if("Y".equals(isInternal)) {
			Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null, sendUserId);
			if(empResult.getCode() == 10000 && empResult.getData() != null && empResult.getData().getUser() != null) {
				EmployeeVO employeeVO = empResult.getData();
				sendUserName = employeeVO.getUser().getName();
			}else {
				sendUserName = sendUserId;
			}
		}else if(StringUtils.isNotEmpty(sendUserId)){
			Result<SysUserMap> sendUserResult = sysCenterApi.getUserMap(sysCode, "default", sendUserId);
			if(sendUserResult.getCode() == 10000 && sendUserResult.getData() != null) {
				sendUserName = sendUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				sendUserName = sendUserId;
			}
		}
		
		// 当前审批人名称
		if("Y".equals(isInternal)) {
			Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null, handleUserId);
			if(empResult.getCode() == 10000 && empResult.getData() != null && empResult.getData().getUser() != null) {
				EmployeeVO employeeVO = empResult.getData();
				sendUserName = employeeVO.getUser().getName();
				createdBy = employeeVO.getUser().getUserAccountId();
			}else {
				sendUserName = sendUserId;
			}
		}else {
			Result<SysUserMap> handleUserResult = sysCenterApi.getUserMap(sysCode, "default", handleUserId);
			if(handleUserResult.getCode() == 10000 && handleUserResult.getData() != null) {
				handleUserName = handleUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				handleUserName = handleUserId;
			}
			createdBy = handleUserResult.getData().getUserId();
		}
		
		// 校验
		UtaskInfoEntity utaskInfo = utaskInfoMapper.getTask(sysCode, sysTaskId, UnionTaskVar.TASK_UNDO);
		if(utaskInfo == null) {
			throw new MessageException("待办未找到或已审批");
		}
		
		// 更新待办
		utaskInfoEntity.setTaskId(utaskInfo.getTaskId());
		utaskInfoEntity.setSendUserId(sendUserId);
		utaskInfoEntity.setSendUserName(sendUserName);
		utaskInfoEntity.setHandleUserId(handleUserId);
		utaskInfoEntity.setHandleUserName(handleUserName);
		utaskInfoEntity.setLastUpdatedBy(createdBy);
		utaskInfoEntity.setLastUpdateDate(new Date());
		utaskInfoEntity.setLastUpdatedByName(handleUserName);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void updateAchTask(UtaskInfoEntity utaskInfoEntity) throws Exception {
		
		// 转换用户
		String sysTaskId = utaskInfoEntity.getSysTaskId();
		String sysCode = utaskInfoEntity.getSysCode();
		String sendUserId = utaskInfoEntity.getSendUserId();
		String sendUserName = utaskInfoEntity.getSendUserName();
		String handleUserId = utaskInfoEntity.getHandleUserId();
		String handleUserName = utaskInfoEntity.getHandleUserName();
		String isInternal = utaskInfoEntity.getIsInternal();
		Integer createdBy = null; 
		
		// 上一环节审批人名称
		if("Y".equals(isInternal)) {
			Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null, sendUserId);
			if(empResult.getCode() == 10000 && empResult.getData() != null && empResult.getData().getUser() != null) {
				EmployeeVO employeeVO = empResult.getData();
				sendUserName = employeeVO.getUser().getName();
			}else {
				sendUserName = sendUserId;
			}
		}else if(StringUtils.isNotEmpty(sendUserId)){
			Result<SysUserMap> sendUserResult = sysCenterApi.getUserMap(sysCode, "default", sendUserId);
			if(sendUserResult.getCode() == 10000 && sendUserResult.getData() != null) {
				sendUserName = sendUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				sendUserName = sendUserId;
			}
		}
		
		// 当前审批人名称
		if("Y".equals(isInternal)) {
			Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null, handleUserId);
			if(empResult.getCode() == 10000 && empResult.getData() != null && empResult.getData().getUser() != null) {
				EmployeeVO employeeVO = empResult.getData();
				sendUserName = employeeVO.getUser().getName();
				createdBy = employeeVO.getUser().getUserAccountId();
			}else {
				sendUserName = sendUserId;
			}
		}else {
			Result<SysUserMap> handleUserResult = sysCenterApi.getUserMap(sysCode, "default", handleUserId);
			if(handleUserResult.getCode() == 10000 && handleUserResult.getData() != null) {
				handleUserName = handleUserResult.getData().getName().toString();
			}else if(StringUtils.isEmpty(sendUserName)){
				handleUserName = handleUserId;
			}
			createdBy = handleUserResult.getData().getUserId();
		}
		
		
		// 校验
		UtaskInfoEntity utaskInfo = utaskInfoMapper.getTask(sysCode, sysTaskId, UnionTaskVar.TASK_DONE);
		if(utaskInfo == null) {
			throw new MessageException("已办未找到或已审批");
		}
		
		// 更新待办
		utaskInfoEntity.setTaskId(utaskInfo.getTaskId());
		utaskInfoEntity.setSendUserId(sendUserId);
		utaskInfoEntity.setSendUserName(sendUserName);
		utaskInfoEntity.setHandleUserId(handleUserId);
		utaskInfoEntity.setHandleUserName(handleUserName);
		utaskInfoEntity.setLastUpdatedBy(createdBy);
		utaskInfoEntity.setLastUpdateDate(new Date());
		utaskInfoEntity.setLastUpdatedByName(handleUserName);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	public Map<String, List<UtaskInfoEntity>> battchUpdateTask(List<UtaskInfoEntity> taskInfoList) throws Exception {
		
		Map<String, List<UtaskInfoEntity>> resultMap = new HashMap<String, List<UtaskInfoEntity>>();
		List<UtaskInfoEntity> successList = new ArrayList<UtaskInfoEntity>();
		List<UtaskInfoEntity> errorList = new ArrayList<UtaskInfoEntity>();
		
		for (UtaskInfoEntity utaskInfoEntity : taskInfoList) {
			try {
				updateTask(utaskInfoEntity);
				successList.add(utaskInfoEntity);
			} catch (Exception e) {
				errorList.add(utaskInfoEntity);
			}
		}
		
		resultMap.put("success", successList);
		resultMap.put("error", errorList);
		
		return resultMap;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void completeTask(UtaskCompleteTaskParam param) throws Exception {
		
		String sysTaskId = param.getSysTaskId();
		String sysCode = param.getSysCode();
		String appUrl = param.getAppUrl();
		String pcUrl = param.getPcUrl();
		Date handleTime = param.getHandleTime();
		String completeFrom = param.getCompleteFrom();
		
		UtaskInfoEntity utaskInfoEntity = utaskInfoMapper.getTask(sysCode, sysTaskId, UnionTaskVar.TASK_UNDO);
		if(utaskInfoEntity == null) {
			throw new MessageException("待办未找到或已审批");
		}
		
		if(!StringUtils.isEmpty(appUrl)) utaskInfoEntity.setAppUrl(appUrl);
		if(!StringUtils.isEmpty(pcUrl)) utaskInfoEntity.setPcUrl(pcUrl);
		utaskInfoEntity.setHandleTime(handleTime);
		utaskInfoEntity.setCompleteFrom(completeFrom);
		utaskInfoEntity.setState(UnionTaskVar.TASK_DONE);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	public Map<String, List<String>> battchCompleteTask(List<UtaskCompleteTaskParam> paramList) throws Exception {
		
		Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
		List<String> successList = new ArrayList<String>();
		List<String> errorList = new ArrayList<String>();
		
		for (UtaskCompleteTaskParam param : paramList) {
			try {
				completeTask(param);
				successList.add(param.getSysTaskId());
			} catch (Exception e) {
				errorList.add(param.getSysTaskId());
			}
		}
		
		resultMap.put("success", successList);
		resultMap.put("error", errorList);
		
		return resultMap;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void cancelTask(UtaskCompleteTaskParam param) throws Exception {
		
		String sysTaskId = param.getSysTaskId();
		String sysCode = param.getSysCode();
		String appUrl = param.getAppUrl();
		String pcUrl = param.getPcUrl();
		Date handleTime = param.getHandleTime();
		String completeFrom = param.getCompleteFrom();
		
		UtaskInfoEntity utaskInfoEntity = utaskInfoMapper.getTask(sysCode, sysTaskId, UnionTaskVar.TASK_UNDO);
		if(utaskInfoEntity == null) {
			throw new MessageException("待办未找到或已审批");
		}
		
		if(!StringUtils.isEmpty(appUrl)) utaskInfoEntity.setAppUrl(appUrl);
		if(!StringUtils.isEmpty(pcUrl)) utaskInfoEntity.setPcUrl(pcUrl);
		utaskInfoEntity.setHandleTime(handleTime);
		utaskInfoEntity.setCompleteFrom(completeFrom);
		utaskInfoEntity.setState(UnionTaskVar.TASK_CANCEL);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void cancelAchTask(UtaskCompleteTaskParam param) throws Exception {
		
		String sysTaskId = param.getSysTaskId();
		String sysCode = param.getSysCode();
		String appUrl = param.getAppUrl();
		String pcUrl = param.getPcUrl();
		Date handleTime = param.getHandleTime();
		String completeFrom = param.getCompleteFrom();
		
		UtaskInfoEntity utaskInfoEntity = utaskInfoMapper.getTask(sysCode, sysTaskId, UnionTaskVar.TASK_DONE);
		if(utaskInfoEntity == null) {
			throw new MessageException("已办未找到或已审批");
		}
		
		if(!StringUtils.isEmpty(appUrl)) utaskInfoEntity.setAppUrl(appUrl);
		if(!StringUtils.isEmpty(pcUrl)) utaskInfoEntity.setPcUrl(pcUrl);
		utaskInfoEntity.setHandleTime(handleTime);
		utaskInfoEntity.setCompleteFrom(completeFrom);
		utaskInfoEntity.setState(UnionTaskVar.TASK_CANCEL);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	public Map<String, List<String>> battchCancelTask(List<UtaskCompleteTaskParam> paramList) throws Exception {
		
		Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
		List<String> successList = new ArrayList<String>();
		List<String> errorList = new ArrayList<String>();
		
		for (UtaskCompleteTaskParam param : paramList) {
			try {
				cancelTask(param);
				successList.add(param.getSysTaskId());
			} catch (Exception e) {
				errorList.add(param.getSysTaskId());
			}
		}
		
		resultMap.put("success", successList);
		resultMap.put("error", errorList);
		
		return resultMap;
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void updateTaskState(String sysCode, String sysTaskId, String state) throws Exception {
		
		UtaskInfoEntity utaskInfoEntity = utaskInfoMapper.getTask(sysCode, sysTaskId, null);
		if(utaskInfoEntity == null) {
			throw new MessageException("待办未找到");
		}
		
		utaskInfoEntity.setHandleTime(new Date());
		utaskInfoEntity.setState(state);
		utaskInfoMapper.updateById(utaskInfoEntity);
	}

	@Override
	public UtaskInfoEntity getTask(String sysCode, String sysTaskId) throws Exception{
		return utaskInfoMapper.getTask(sysCode, sysTaskId, null);
	}

	@Override
	public Page<UtaskInfoEntity> getTaskInfoList(QueryUtaskParam param) throws Exception{
		
		String sysCodeFrom = param.getSysCodeFrom();
		String sysCode = param.getSysCode();
		String userCode = param.getUserCode();
		Integer userId = null;
		
		if("default".equals(sysCodeFrom)) {
			Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(null, userCode);
			if(empResult.getCode() == 10000 && empResult.getData() != null && empResult.getData().getUser() != null) {
				EmployeeVO employeeVO = empResult.getData();
				userId = employeeVO.getUser().getUserAccountId();
			}
		}else {
			Result<SysUserMap> sysUserResult = sysCenterApi.getUserMap(sysCodeFrom, "default", userCode);
			if(sysUserResult.getCode() == 10000 && sysUserResult.getData() != null) {
				SysUserMap sysUserMap = sysUserResult.getData();
				userId = sysUserMap.getUserId();
			}
		}
		
		if("default".equals(sysCode)) {
			param.setSysCode(null);
		}
		
		if(userId == null) {
			throw new Exception("用户转换失败，未获取到用户信息");
		}else {
			param.setUserCode(userId.toString());
		}
		
    	Page<UtaskInfoEntity> utaskInfoPage = UtaskCommonFun.getPage(param.getFirst(), param.getLimit());
    	
		List<UtaskInfoEntity> utaskInfoList = utaskInfoMapper.findList(utaskInfoPage, param);
		
		return utaskInfoPage.setRecords(utaskInfoList);
	}

	@Override
	public Integer getTaskInfoListNum(QueryUtaskParam param) throws Exception{
		return utaskInfoMapper.getTaskInfoListNum(param);
	}

	@Override
	public List<Map<String, Object>> selectTaskCountList(QueryUtaskParam param) throws Exception{
		return utaskInfoMapper.selectTaskCountList(param);
	}

	@Override
	public String getTaskState(String sysCode, String sysTaskId) throws Exception{
		
		UtaskInfoEntity utaskInfoEntity = utaskInfoMapper.getTask(sysCode, sysTaskId, null);
		if(utaskInfoEntity == null) {
			throw new MessageException("未找到数据");
		}
		
		return utaskInfoEntity.getState();
	}

	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void collectTask(String userCode, String taskId, String sysCodeFrom, String flag) throws Exception {
		
	}
	
	@Override
	public UtaskInfoEntity getUtaskInfoById(String taskId) throws Exception{
		return utaskInfoMapper.selectById(taskId) ;
	}
}
